package com.sx.guavatest.service;

import com.sx.guavatest.beans.JobBean;
import com.sx.guavatest.cache.LocalCache;
import com.sx.guavatest.dao.JobDetailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author shengx
 * @date 2020/8/8 9:26
 */
@Service
public class JobDetailServiceImpl implements JobDetailService{
    @Autowired
    private JobDetailRepository jobDetailRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LocalCache localCache;


    @Override
    public List<JobBean> getMainHotJob(Integer position) {
        // 1.从本地guava cache中获取
        String cacheKey = "job:main";
        List<JobBean> jobBeans = localCache.get(cacheKey);
        // 2.本地获取不到从redis中获取，获取到回写到guava cache
        if(jobBeans == null || jobBeans.isEmpty()){
            System.out.println("本地cache空，尝试从redis中获取");
            Object o = redisTemplate.opsForValue().get(cacheKey);
            if(o!=null){
                System.out.println("从redis中查出：" + o);
                localCache.add(cacheKey, (List<JobBean>) o);
                return (List<JobBean>) o;
            }else{
                // 3.redis也获取不到，从db获取，并回写redis和本地缓存
                List<JobBean> jobBeansByPid = jobDetailRepository.findJobBeansByPid(position);
                System.out.println("从DB查出：" + jobBeansByPid);

                redisTemplate.opsForValue().setIfAbsent(cacheKey, jobBeansByPid, 60, TimeUnit.SECONDS);
                localCache.add(cacheKey, jobBeansByPid);
                return jobBeansByPid;
            }
        }else{
            // 直接从本地缓存
            System.out.println("从本地缓存获取到，直接返回");
            return jobBeans;
        }
    }

    @Override
    public void addMainHotJob(JobBean jobBean) {
        // 1.先把本地缓存和redis删除
        String cacheKey = "job:main";
        localCache.remove(cacheKey);
        redisTemplate.delete(cacheKey);
        jobDetailRepository.save(jobBean);
    }
}
